package com.lanhao.aot.anthouse;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import cn.hutool.core.codec.Base64;

/**
 * ZeroPadding填充
 */
public class AESUtil {

	private static final String KEY_ALGORITHM = "AES";
	private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/NoPadding";// 默认的加密算法

	public static String encodeByKey(String plainText, String keyStr) {
		   byte[] encrypt = null;
		   try {
		      if (plainText == null || plainText.length() == 0 || keyStr == null || (keyStr.length() % 16) != 0) {
		         return null;
		      } else {
		         SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(), KEY_ALGORITHM);
		         Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
		         cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		         int pad = plainText.getBytes().length % 16;
		         if (pad != 0) {
		            for (int i = 0; i < 16 - pad; i++) {
		               plainText = plainText + "\0";
		            }
		         }
		         byte c[] = plainText.getBytes();
		         encrypt = cipher.doFinal(plainText.getBytes());
		      }
		   } catch (Exception e) {
		      e.printStackTrace();
		   }
		   return new String(Base64Utils.encode(encrypt));
		}

		public static String getDecodeByKey(String encryptData, String keyStr) {
		   byte[] decrypt = null;
		   try {
		      if (encryptData == null || encryptData.length() == 0 || keyStr == null || (keyStr.length() % 16) != 0) {
		         return null;
		      } else {
		         SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(), "AES");
		         Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
		         cipher.init(Cipher.DECRYPT_MODE, keySpec);
		         decrypt = cipher.doFinal(Base64Utils.decode(encryptData));
		      }
		   } catch (Exception e) {
		      e.printStackTrace();
		   }
		   if (decrypt == null)
		      return null;
		   else
		      return new String(decrypt).trim();
		}

	public static void main(String[] args) throws UnsupportedEncodingException {
//		String data = "ZKEffg3IJSU08rSuDAx3uthiGWMVfprOb%2FzYl57PyIvEqnQDUmLhLW1uUSJYCP6NU7opDBmU4Mz5xN4UW0Ot2TBb7UsWN6Bg90KxhFC5fkZchdG4vAtnEUJlkHB7%2FAfPwKy5d6RkNuaXtEHxkeooxoONCvppsBKoq9xpy2FbGWe+DH0ACXQKj7Hl946j8%2FgG=";
		String data = "a3oGb2P0k6Vi85KUEJHplBSmCVitOVWZWrPuSI4qk+D%2Fr75tBSug6DCLXXS7YsTiIm%2F1PKMxtUGyLytQy4oetWk4cLiS%2FEdCcNTqDHspR8mGTTD0W6BMclzW6oJIao1YtW%2F12SOtuT15ZfRTJCX5T40gHJZsBOuWmvhp1qvqqSU=";
		data = data.replaceAll("%2F", "/");
		System.out.println(data);
		String decodeByKey = getDecodeByKey(data, "aF1PzRqF77DaPn2n");
		System.out.println(decodeByKey);
	}

}